package com.example.controller;

import com.example.config.AppConfig;
import com.example.config.AppFinal;
import com.example.mapper.UserMapper;
import com.example.model.ArticleInfo;
import com.example.model.User;
import com.example.tool.HtmlText;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.util.ClassUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;


@RequestMapping("/user")
@Slf4j
@Controller
public class UserController {

    @Resource
    //Autowired需要一个非空对象，而它引入的是Mybatis，IDEA不能很好识别
    private UserMapper userMapper;

    @Resource
    private ObjectMapper objectMapper;


    @Value("${myimagepath}") //myimagepath是动态的变量，要从application中取值，这里不能写为字符串
    private String imagePath;

    @RequestMapping("/getalist1")
    @ResponseBody
    public Object getFullUser1(int uid){
        return userMapper.getFullUser(uid);
    }

    @RequestMapping("/getalist")
    @ResponseBody
    public Object getFullUser(int uid){
        User user = userMapper.getFullUser(uid);
        //对文章内容进行截取操作，只展示一部分
        List<ArticleInfo> list = user.getAlist();
        //对每个文章进行设置
        for(ArticleInfo articleInfo : list){
            //去掉html标签
            String s = HtmlText.html2Text(articleInfo.getContent());
            //截取字符串
            if(s.length() > 64){
                s = s.substring(0,64)+"......";
            }
            articleInfo.setContent(s);
        }
        user.setAlist(list);
        return user;
    }


    //根据内置的日志框架获取一个当前类的日志对象
    private Logger logger = LoggerFactory.getLogger(UserController.class);

    @RequestMapping("/index")
    @ResponseBody
    public String getIndex(String name){
        if(name == null || name.equals("")){
            logger.error("我的日志信息，级别：error");
        }
        logger.warn("我的日志信息，级别：warn");
        logger.info("我的日志信息，级别：info");
        logger.trace("我的日志信息，级别：trace");
        log.debug("我的日志信息，级别：debug"); //@Slf4j内置log对象
        return "你好，offer";
    }


    @RequestMapping("/login")
    @ResponseBody
    public String login(@RequestBody User user, HttpServletRequest request
    ){
        //判断用户名和密码
        if(user.getUsername().equals("root") && user.getPassword().equals("root")){
            //登录的用户信息保存在Session中
            HttpSession session = request.getSession();
            session.setAttribute("userinfo",user);
            return "登录成功";
        }
        return "登录失败";
    }


    //投机取巧
    @RequestMapping("/login2")
    @ResponseBody
    public Object login2(@RequestParam String name,HttpServletRequest request){

        HashMap<String, Object> map = new HashMap<>();
        //定义返回状态
        int status = -1;
        String msg = "未知错误";
        String data = "登录失败";
        if(name.equals("root")){
            //登录的用户信息保存在Session中
            HttpSession session = request.getSession(); //得到Session
            session.setAttribute("name",name);
            status = 0;
            msg = "";
            data = "登录成功";
        }else{
            status = 0;
            msg = "用户名错误";
            data = "登录失败";
        }
        map.put("status",status);
        map.put("msg",msg);
        map.put("data",data);
        return map;
    }

    //课堂练习
    @RequestMapping("/login3")
    @ResponseBody
    public Object login3(User user,HttpServletRequest request){

        HashMap<String, Object> map = new HashMap<>();  //Spring支持直接把对象转成前端的Json对象
        //定义返回状态
        int status = -1; //飞正常状态返回
        String msg = "未知错误";
        String data = "登录失败";
        if(user != null && user.getUsername().equals("trq") && user.getPassword().equalsIgnoreCase("0627")){
            //登录的用户信息保存在Session中
            HttpSession session = request.getSession(); //得到Session
            session.setAttribute(AppFinal.USERINFO_SESSIONKEY,user); //设置session信息，用常量表示不易出错
            status = 0;
            msg = "";
            data = "登录成功";
        }else{
            status = 0;
            msg = "用户名错误";
            data = "登录失败";
        }
        map.put("status",status);
        map.put("msg",msg);
        map.put("data",data);
        return map;
    }


    @RequestMapping("/login4")
    @ResponseBody
    /**
     * spring框架将前端传过来的参数封装成一个对象，对象中只有username和password
     */
    //返回值修改为Object，如果返回String，前端拿到的还是Json字符串。。。
    public Object login4(User user, HttpServletRequest request) throws JsonProcessingException {
        //得到User对象
        User user1 = userMapper.getUserByNameAndPassword(user.getUsername(), user.getPassword());
        //当查询出的user1为null时，将封装的前端传递过来的对象赋值给user1；因为当user1为null时不会执行数据格式封装
        if(user1 == null){
            user1 = user;
        }else{
            //登录成功之后设置session信息
            HttpSession session = request.getSession();
            session.setAttribute(AppFinal.USERINFO_SESSIONKEY,user1); //这里是session键值对，把用户内容存在session中
        }
        return user1;
    }

    //注册
    @RequestMapping("/reg")
    //之前加了ResponseBody返回了Json字符串，没有返回视图，一定要记住
    public String register(String username, String password, @RequestPart MultipartFile file

    ) throws IOException {
        //Todo 非空效验
        //1.动态获取当前项目的路径
        //这里得到的是target下static的目录，因为IDEA运行时运行的是target目录
//        String path = ClassUtils.getDefaultClassLoader().getResource("static").getPath();
        String path = imagePath;
        path += AppFinal.IMAGE_PATH;
        log.error("path"+path); //打印出路径

        //2.文件名（全局唯一，时间戳是不可以的，可以使用UUID） + 文件的原始类型（比如jpg/png）
        String fileType = file.getOriginalFilename(); //例如拿到img.jpg
        fileType = fileType.substring(fileType.lastIndexOf(".")); //拿到.jpg
        String fileName = UUID.randomUUID().toString() + fileType; //拿到文件名称
        //将文件保存在服务器
        file.transferTo(new File(path+fileName));  //传入文件路径

        User user = new User();
        user.setUsername(username);  //这里的username是前端传递过来的，password也是
        user.setPassword(password);
        user.setPhoto(AppFinal.IMAGE_PATH + fileName);  //设置的头像地址，相对的url地址，前端将其和url拼接
        int result = userMapper.addUser(user);
        if(result > 0){
            return "redirect:/login.html";
        }else{
            return "redirect:/reg_error.html";
        }
    }

    @RequestMapping("/getcookie")
    @ResponseBody
    public Object getCookie(@CookieValue("mySessionId") String cookieId){
        return cookieId;
    }



    @RequestMapping("/test")
    @ResponseBody
    public Object test(){
        int i = 10/0;
        return "hello";
    }


    //这里稍微有那么一点不清晰
    @RequestMapping("/method")
    @ResponseBody
    public Object method(){
//        HashMap<String, Object> map = new HashMap<>();

        //data就是MyResponseBodyAdvice类中beforeBodyWrite的对象o,o是返回给服务器端的数据
        Object data = "method";
//        map.put("status",0);
//        map.put("data",data);
//        map.put("msg","");
        return data;
    }

//    @RequestMapping("/getalist")
//    @ResponseBody
//    public Object getFullUser(int uid) {
//        User user = userMapper.getFullUser(uid);
//        // 对文章的正文进行截取操作
//        List<ArticleInfo> list = user.getAlist();
//        for (ArticleInfo item : list) {
//            // 去除html标签
//            String desc = HtmlText.Html2Text(item.getContent());
//            // 截取字符串
//            if (desc.length() > 64) {
//                desc = desc.substring(0, 64) + "...";
//            }
//            item.setContent(desc);
//        }
//        user.setAlist(list);
//        return user;
//    }







}
